#include <unistd.h> 
#include <signal.h> 
#include <sys/param.h> 
#include <sys/types.h> 
#include <sys/stat.h> 
#include <time.h>
#include <stdio.h>
#include <stdlib.h>

#include <zmq.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <assert.h>
  
void init_daemon(void) 
{ 
	int pid; 
	int i;
	pid = fork();
	printf("pid=%d\n", pid);
	if(pid != 0)
	{
		printf("parent process %d exit\n", getpid());
		exit(0);//是父进程，结束父进程
	}
	else if(pid < 0) 
	{
		exit(1);//fork失败，退出
	}
	printf("%d detach from parent process, now parent=%d\n", getpid(), getppid());

	//是第一子进程，后台继续执行 
	setsid();//第一子进程成为新的会话组长和进程组长 

	//并与控制终端分离 
	pid = fork();
	printf("pid=%d\n", pid);
	if(pid != 0) 
	{
		printf("child process %d exit\n", getpid());
		exit(0);//是第一子进程，结束第一子进程
	}
	else if(pid< 0) 
	{
		exit(1);//fork失败，退出
	}
	printf("%d detach from child process, now parent=%d\n", getpid(), getppid());

	//是第二子进程，继续 
	//第二子进程不再是会话组长 

	for(i=0; i<NOFILE; ++i)//关闭打开的文件描述符 
	{
		close(i);
	}


	signal(SIGCHLD,SIG_IGN);
	signal(SIGHUP,SIG_IGN);

	chdir("/tmp");//改变工作目录到/tmp 
	umask(0);//重设文件创建掩模 
}

int main (void)
{
    init_daemon();

    //  Socket to talk to clients
    void *context = zmq_ctx_new ();
    void *responder = zmq_socket (context, ZMQ_REP);
    int rc = zmq_bind (responder, "tcp://*:5555");
    assert (rc == 0);

    while (1) {
        char buffer [10];
        zmq_recv (responder, buffer, 10, 0);
        printf ("Received Hello\n");
        sleep (1);          //  Do some 'work'
        zmq_send (responder, "World", 5, 0);
    }
    return 0;
}

